import { Button, Flex, Table, Upload, message } from "antd";
import { UploadProps, UploadFile } from "antd/lib";
import React, { useState } from "react";
import * as XLSX from 'xlsx'
import ExportJsonExcel from 'js-export-excel';
const execl = () => {
    const [source, setScource] = useState();
    const [columns, setColumns] = useState([]);

    // 解析excel   npm i xlsx
    const handleUpload = (file: Blob) => {
        const reader = new FileReader();
        reader.onload = (e: any) => {
            const binaryStr = e.target.result;
            const workbook = XLSX.read(binaryStr, { type: "binary" });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            // 将工作表转换为 JSON 格式
            const jsonData: any = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

            const columns = jsonData[0].map((item: [string]) => {
                return {
                    title: item,
                    dataIndex: item,
                }
            })
            const list = jsonData.slice(1).map((item: any, index: any) => {
                const rowData: any = {};
                item.forEach((value: any, ceallIndex: any) => {
                    rowData[jsonData[0][ceallIndex]] = value;
                })
                return { key: index, ...rowData }
            })
            setScource(list);
            setColumns(columns)
        };

        reader.onerror = () => {
            message.error("文件读取失败");
        };

        reader.readAsBinaryString(file);
        return false; // Prevent default upload behavior
    };

    // 上传解析excel    
    const [fileList, setFileList] = useState<UploadFile[]>([])

    const uploadType: UploadProps = {
        beforeUpload: (file) => {   
            // 判断是否为开发环境
            // import.meta.env.xxx === 'dev'

            // 后台传递
            // const formData = new FormData()
            // formData.append('file', file)
            console.log(file);

            setFileList([file])
            return false
        },
    }


    const onExprotExcel = () => {
        if (source) { //data是数组需要导出的数据
            const getRepaymentPlanList = JSON.parse(JSON.stringify(source))
            const option: any = []; //option代表的就是excel文件
            option.fileName = "文件命名"
            const sheetData = getRepaymentPlanList; // 有需要映射的话需要先映射
            let sheetFilter:string[] = [];
            Object.keys(source[0]).forEach((item) => {
                sheetFilter.push(item)
            })
            
            const sheetHeader:string[] = [];
            Object.keys(source[0]).forEach((item) => {
                sheetHeader.push(item);
            })
            option.datas = [{
                sheetData,
                sheetName: "个人信息表",
                sheetFilter,
                sheetHeader,
                columnWidth: new Array(sheetHeader.length).fill(20),
            }];

            let toExcel = new ExportJsonExcel(option);  // 生成excel文件
            toExcel.saveExcel();  // 下载excel文件 
        }
    }

    return <div>
        <Flex gap={'middle'}>
            <Upload {...uploadType}>
                {fileList.length === 0 ? <Button>{'请上传Excel'}</Button> : ''}
            </Upload>
            {fileList.length !== 0 ? (
                <Button type="primary">
                    {'上传并计算'}
                </Button>
            ) : (
                <></>
            )}
            <Upload beforeUpload={handleUpload} showUploadList={false}>
                <Button>{'上传并渲染excel表格'}</Button>
            </Upload>

            <Button disabled={!source} onClick={onExprotExcel}>{'导出excel表格'}</Button>
        </Flex>
        <Table
            dataSource={source}
            columns={columns}
            pagination={false}
            style={{ marginTop: 20 }}
        />
    </div>
}

export default execl